#  RAMP Media Organizer  
#  Scanner.py
#
#  Copyright (C) 2010  Vishesh Yadav  
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import sys

from PyQt4 import QtCore
from mutagen.easyid3 import EasyID3 
from mutagen.id3 import ID3NoHeaderError 

from Database import Database

class Scanner(QtCore.QThread):
    def __init__(self, directory, dbFileName):
        QtCore.QThread.__init__(self)
        self.target = directory
        self.directory = QtCore.QDir(directory)
        self.dbFileName = dbFileName
        self.audio = None
        self.runFlag = True
        
        filters = QtCore.QStringList()
        filters << "*.mp3"

        self.directory.setNameFilters(filters)
        self.directory.setFilter(QtCore.QDir.AllEntries)

    
    def GetTag(self, tag):
        try:
            return self.audio[tag][0]
        except:
            return ""

    def GetDetailsForFile(self, fileName):
        try: 
            self.audio = EasyID3(fileName)
            lst = ( self.GetTag('title'), self.GetTag('artist'), 
                    self.GetTag('album'), self.GetTag('genre'), 
                    self.GetTag('year'), '', fileName)
            return lst
        except ID3NoHeaderError as err:
            return ('',)*6 + (fileName, )


    def CancelScanning(self):
        print "Cancelling Scanner Thread."
        self.runFlag = False

    def IsScanning(self):
        return self.runFlag
    

    def AddFilesToDb(self):
        print "Started Scanning"
        iterator = QtCore.QDirIterator(self.directory, QtCore.QDirIterator.Subdirectories)
        db = Database(self.dbFileName, True)
        db.OpenCursor()
        self.runFlag = True
        while iterator.hasNext() and self.runFlag:
            x = iterator.next()
            try:
                ent = self.GetDetailsForFile(unicode(x))
                db.InsertEntry(*ent)
            except KeyError:
                pass
        db.CloseSaveCursor()
        print "Scanning Over"

    def run(self):
        self.AddFilesToDb()
    
